import React, { PureComponent } from 'react';
import _ from 'lodash';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, message } from 'antd';
import { PrimaryGhostC, FirstHeaderC, SecondHeaderC, PrimaryC, DATA_ENTRY, FormGroup, FixedButtonC } from '../../../comps';
import { connect } from 'dva';
import AssetPackage from './assetPackage'; //资产包
// import ValuateAnalysisInfo from '../qualificationManagementPlanMaintenance/valuateAnalysisInfo';//估值解析
import ValuateAnalysisInfo from '../valuationAnalysis/valuateAnalysisInfo'; //估值解析
import moment from 'moment';

@Form.create()
@connect(({ OutsourceInvestMsgMaintainM, loading, globalM }) => ({ OutsourceInvestMsgMaintainM, loading, globalM }))
export default class updateModelC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isExpectReturnFlag: '0', //【是否有预期收益率】为是时：预期最高收益和预期最低收益 必填，为否时：预期最高收益和预期最低收益 置灰
      investStartDate: undefined, //投资计划终止日期的禁选起始日期
      investEndDate: undefined, //投资计划成立日期的禁选结束日期
      editObj: undefined, //编辑时的数据
      valuateAnalysisHide: false, // 详情时如果 委外投资属性是 集合管理，估值解析隐藏
      isReportFlag: false, //是否有监管报表权限
    };
  }
  componentDidMount() {
    this.props.onRef(this);
    // 判断当前登录用户是否有监管报表权限
    if (this.props.type == '2' || this.props.type == '3') {
      // 编辑或详情时 调该接口获取基础信息和监管报表信息
      this.props.dispatch({
        type: 'OutsourceInvestMsgMaintainM/getDataById',
        payload: {
          id: this.props.operateId,
        },
        callback: (type, res) => {
          if (type == 'success') {
            if (JSON.stringify(res) !== '{}' && res) {
              this.setState({
                // 处理起始终止日期在编辑时的禁用逻辑
                investStartDate: res.investPlanSetupDate ? moment(res.investPlanSetupDate) : undefined,
                investEndDate: res.investPlanTerminateDate ? moment(res.investPlanTerminateDate) : undefined,
                // 处理是否有预期收益率在编辑时的逻辑
                isExpectReturnFlag: res.isExpectReturn ? res.isExpectReturn : '0',
              });
              // 详情时如果 委外投资属性是 集合管理，估值解析隐藏
              if (this.props.type == '3' && res.outsourceInvestProperty == '01') {
                // 详情
                this.setState({
                  valuateAnalysisHide: true,
                });
              }
            }
            this.setState({
              editObj: res,
            });
          }
        },
      });
    }
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  // 返回主页面
  onBack = (type) => {
    this.props.onBack(false, type);
  };

  // 取消点击事件
  onCancel = () => {
    this.onBack('cancel');
  };
  // 确认按钮点击事件
  onOk = () => {
    const { type } = this.props;
    if (type == 3) {
      // 查看详情
      this.onBack('cancel');
    } else if (type == 1 || type == 2) {
      // 新增或编辑
      let baseFieldsValue = this.baseInfoRef.getFormGroupData();
      let superviseFieldsValue = this.superviseStateInfoRef.getFormGroupData();
      if (baseFieldsValue && superviseFieldsValue) {
        let superviseStateInfoData = superviseFieldsValue;
        let assetPackageData = this.state.assetPackageRef?.getInfo();
        if (assetPackageData == null) return;
        if (JSON.stringify(superviseStateInfoData) != {}) {
          // 遍历报表信息对象，处理值
          for (var key in superviseStateInfoData) {
            if (key == 'money') {
              superviseStateInfoData[key] = Number(superviseStateInfoData[key]).toFixed(2);
            }
            if (key == 'shareFaceValue') {
              superviseStateInfoData[key] = Number(superviseStateInfoData[key]).toFixed(4);
            }
            if (
              key == 'expectMaxReturn' ||
              key == 'expectLowReturn' ||
              key == 'manageFeeRate' ||
              key == 'trustFeeRate' ||
              key == 'dealRelateFeeRate' ||
              key == 'agencyFeeRate' ||
              key == 'otherFeeRate'
            ) {
              superviseStateInfoData[key] = Number(superviseStateInfoData[key] / 100).toFixed(7);
            }
            if (key == 'investPlanSetupDate' || key == 'investPlanTerminateDate') {
              // 投资计划成立日期 投资计划终止日期格式
              superviseStateInfoData[key] = superviseStateInfoData[key] ? superviseStateInfoData[key].format('YYYY-MM-DD') : undefined;
            }
          }
        }
        if (JSON.stringify(baseFieldsValue) != {}) {
          // 遍历基本信息，处理值
          for (var key in baseFieldsValue) {
            if (key == 'money') {
              baseFieldsValue[key] = Number(baseFieldsValue[key]).toFixed(2);
            }
            if (key == 'shareFaceValue') {
              baseFieldsValue[key] = Number(baseFieldsValue[key]).toFixed(4);
            }
          }
        }

        if (type == 1) {
          // 新增
          this.props.dispatch({
            type: 'OutsourceInvestMsgMaintainM/saveData',
            payload: {
              ...baseFieldsValue,
              ...superviseStateInfoData,
              titleValue: assetPackageData, //资产包数据
            },
            callback: (type) => {
              if (type == 'success') {
                // 重置，
                this.onBack('ok');
              }
            },
          });
        } else if (type == 2) {
          // 编辑
          this.props.dispatch({
            type: 'OutsourceInvestMsgMaintainM/editData',
            payload: {
              id: this.props.operateId,
              ...baseFieldsValue,
              ...superviseStateInfoData,
              titleValue: assetPackageData, //资产包数据
            },
            callback: (type) => {
              if (type == 'success') {
                // 重置，
                this.onBack('ok');
              }
            },
          });
        }
      } else {
        return false;
      }
    }
  };
  // 预期最高收益率校验（最小值限制）
  handleMaxValidator = (rule, val, callback) => {
    const {
      form: { getFieldValue },
    } = this.superviseStateInfoRef.props;
    if (parseFloat(val) < parseFloat(getFieldValue('expectLowReturn'))) {
      callback('输入值不能小于最低收益率！');
    }
    callback();
  };
  // 预期最低收益率校验（最大值限制）
  handleMinValidator = (rule, val, callback) => {
    const {
      form: { getFieldValue },
    } = this.superviseStateInfoRef.props;
    if (parseFloat(val) > parseFloat(getFieldValue('expectMaxReturn'))) {
      callback('输入值不能大于最高收益率！');
    }
    callback();
  };
  // 用户基本信息
  baseInfo = () => {
    const {
      OutsourceInvestMsgMaintainM: { assetType, splitWayList },
      type,
    } = this.props;
    const { editObj } = this.state;
    return (
      <>
        <SecondHeaderC title='基础信息' />
        <FormGroup
          dataSource={[
            {
              dataIndex: 'tradingCode',
              title: '证券代码',
              helper: '若需出具监管报表，请填写报表中对应登记编码',
              type: DATA_ENTRY.INPUT,
              max: 255,
              initialValue: type == 1 ? undefined : editObj?.tradingCode,
              disabled: type == 3 || type == 2 ? true : false,
              rules: [
                {
                  required: true,
                  message: '请输入证券代码',
                },
              ],
            },
            {
              dataIndex: 'secuabbr',
              title: '证券名称',
              helper: '请填写合同文件中注明的资管计划全称，请不要填写计划的简称',
              type: DATA_ENTRY.INPUT,
              max: 200,
              initialValue: type == 1 ? undefined : this.state.editObj?.secuabbr,
              disabled: type == 3 ? true : false,
              rules: [{ required: true, message: '请输入证券名称' }],
            },
            {
              dataIndex: 'assetType',
              title: '资产类别',
              type: DATA_ENTRY.SELECT,
              dataSource: assetType,
              initialValue: type == 1 ? undefined : this.state.editObj?.assetType,
              disabled: type == 3 ? true : false,
              allowClear: true,
              rules: [
                {
                  required: true,
                  message: '请选择资产类别',
                },
              ],
            },
            {
              dataIndex: 'outsourcedAssetNum',
              title: '委外资产编号',
              type: DATA_ENTRY.INPUT,
              max: 40,
              initialValue: type == 1 ? undefined : this.state.editObj?.outsourcedAssetNum,
              disabled: type == 3 ? true : false,
              rules: [{ required: true, message: '请输入委外资产编号' }],
            },
            {
              dataIndex: 'money',
              title: '金额',
              helper: '委外投资协议中约定的投资金额',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '元',
              splitStyle: true,
              precision: 2,
              max: 999999999999.99,
              initialValue: type == 1 ? undefined : this.state.editObj?.money,
              disabled: type == 3 ? true : false,
              rules: [{ required: true, message: '请输入金额!' }],
            },
            {
              dataIndex: 'shareFaceValue',
              title: '份额面额',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: 'CNY',
              min: 0,
              max: 999999999999.9999,
              splitStyle: true,
              precision: 4,
              initialValue: type == 1 ? undefined : this.state.editObj?.shareFaceValue,
              disabled: type == 3 ? true : false,
              rules: [{ required: true, message: '请输入份额面额!' }],
            },
            {
              dataIndex: 'splitWay',
              title: '拆分方式',
              type: DATA_ENTRY.SELECT,
              helper: '用于估值解析后的产品持仓分配',
              dataSource: splitWayList,
              initialValue: type == 1 ? undefined : this.state.editObj?.splitWay,
              disabled: type == 3 ? true : false,
              allowClear: true,
              rules: [{ required: true, message: '请选择拆分方式!' }],
            },
          ]}
          onRef={(ref) => {
            this.baseInfoRef = ref;
          }}
        />
      </>
    );
  };
  // 是否有预期收益率
  isExpectReturnChange = (e) => {
    // 切换时重置  预期最高收益和预期最低收益
    this.superviseStateInfoRef?.props.form.setFieldsValue({
      expectMaxReturn: '',
      expectLowReturn: '',
    });
    // 【是否有预期收益率】为是时：预期最高收益和预期最低收益 必填，为否时：预期最高收益和预期最低收益 置灰
    this.setState({
      isExpectReturnFlag: e,
    });
  };
  // 监管报表信息
  superviseStateInfo = () => {
    const {
      OutsourceInvestMsgMaintainM: { fundActualInvest, outsourceInvestProperty },
      type,
    } = this.props;
    const { isExpectReturnFlag, isReportFlag } = this.state;
    return (
      <>
        <SecondHeaderC title='监管报表信息' />
        <FormGroup
          dataSource={[
            //*********************************  第一行 ********************************************/
            {
              dataIndex: 'assignee',
              title: '受托人',
              type: DATA_ENTRY.INPUT,
              initialValue: type == 1 ? undefined : this.state.editObj?.assignee,
              disabled: type == 3 ? true : false,
              max: 200,
              rules: [{ required: isReportFlag, message: '请输入受托人!' }],
            },
            {
              dataIndex: 'manager',
              title: '管理人',
              type: DATA_ENTRY.INPUT,
              initialValue: type == 1 ? undefined : this.state.editObj?.manager,
              disabled: type == 3 ? true : false,
              max: 200,
              rules: [{ required: isReportFlag, message: '请输入管理人!' }],
            },
            {
              dataIndex: 'trustee',
              title: '托管人',
              type: DATA_ENTRY.INPUT,
              initialValue: type == 1 ? undefined : this.state.editObj?.trustee,
              disabled: type == 3 ? true : false,
              max: 200,
              rules: [{ required: isReportFlag, message: '请输入托管人!' }],
            },
            //*********************************  第二行 ********************************************/
            {
              dataIndex: 'fundActualInvest',
              title: '资金实际投向',
              type: DATA_ENTRY.SELECT,
              dataSource: fundActualInvest,
              initialValue: type == 1 ? undefined : this.state.editObj?.fundActualInvest,
              disabled: type == 3 ? true : false,
              allowClear: true,
              rules: [{ required: isReportFlag, message: '请选择资金实际投向!' }],
            },
            //*********************************  第三行 ********************************************/
            {
              dataIndex: 'fundUseWay',
              title: '资金运用方式',
              type: DATA_ENTRY.INPUT,
              helper:
                '对资金实际投向、投资标的、期限长短等资金运作情况的详细说明。1、本要素需详细介绍资管计划的投资运作等情况，例如： 50%-60% 资金用于投资某债券，投资期限3个月； 40%-50% 资金用于投资某货币市场工具，投资期限 1 个月。2.若资管计划属于伞形信托，需在此处注明“伞形信托”。',
              initialValue: type == 1 ? undefined : this.state.editObj?.fundUseWay,
              disabled: type == 3 ? true : false,
              showTextArea: true,
              lineOne: true,
              max: 300,
              autosize: { minRows: 1, maxRows: 1 },
              rules: [{ required: isReportFlag, message: '请输入资金运用方式!' }],
            },
            //*********************************  第四行 ********************************************/
            {
              dataIndex: 'fundUseIndustry', //资金运用行业
              type: DATA_ENTRY.FUNDAPPLICATIONINDUSTRYC,
              title: '资金运用行业',
              initialValue: type == 1 ? 'J66' : this.state.editObj?.fundUseIndustry,
              disabled: type == 3 ? true : false,
              rules: [{ required: isReportFlag, message: '请选择资金运用行业' }],
            },
            {
              dataIndex: 'investPlanSetupDate',
              title: '投资计划成立日期',
              helper: '委托投资正式开始运作的日期，一般为委外投资协议生效日期。',
              disableEnd: this.state.investEndDate,
              type: DATA_ENTRY.SINGLEDATE,
              initialValue: type == 1 ? undefined : this.state.editObj?.investPlanSetupDate ? moment(this.state.editObj?.investPlanSetupDate) : undefined,
              disabled: type == 3 ? true : false,
              onChange: (e) => {
                this.setState({
                  investStartDate: e,
                });
              },
              rules: [{ required: isReportFlag, message: '请选择投资计划成立日期!' }],
            },
            {
              dataIndex: 'investPlanTerminateDate',
              title: '投资计划终止日期',
              helper: '委托投资运作结束日，一般为委外投资协议终止日期',
              disableBegin: this.state.investStartDate,
              type: DATA_ENTRY.SINGLEDATE,
              initialValue: type == 1 ? undefined : this.state.editObj?.investPlanTerminateDate ? moment(this.state.editObj?.investPlanTerminateDate) : undefined,
              disabled: type == 3 ? true : false,
              onChange: (e) => {
                this.setState({
                  investEndDate: e,
                });
              },
              rules: [{ required: isReportFlag, message: '请选择投资计划终止日期!' }],
            },
            //*********************************  第五行 ********************************************/
            {
              dataIndex: 'outsourceInvestProperty',
              title: '委外投资属性',
              type: DATA_ENTRY.SELECT,
              dataSource: outsourceInvestProperty,
              initialValue: type == 1 ? undefined : this.state.editObj?.outsourceInvestProperty,
              disabled: type == 3 ? true : false,
              allowClear: true,
              rules: [{ required: isReportFlag, message: '请选择委外投资属性!' }],
            },
            {
              dataIndex: 'isExpectReturn',
              title: '是否有预期收益率',
              type: DATA_ENTRY.SELECT,
              isTrueFalseJudge: true,
              initialValue: type == 1 ? '0' : this.state.editObj?.isExpectReturn,
              disabled: type == 3 ? true : false,
              allowClear: true,
              onChange: (e) => {
                this.isExpectReturnChange(e);
              }, //响应onChange，处理【预期最高收益率】和【预期最低收益率】
              rules: [{ required: isReportFlag, message: '请选择是否有预期收益率!' }],
            },
            {
              dataIndex: 'expectMaxReturn',
              title: '预期最高收益率',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '%',
              splitStyle: true,
              precision: 5,
              max: 99.99999,
              initialValue: type == 1 ? undefined : this.state.editObj?.expectMaxReturn ? Number(this.state.editObj.expectMaxReturn * 100).toFixed(5) : undefined,
              disabled: type == 3 ? true : isExpectReturnFlag == 1 ? false : true,
              rules: [
                // { pattern: /(^-?(?:\d|\d{0,8})(?:\.\d{0,5})?$)/, message: '字符不能超过8位！' },
                { required: isExpectReturnFlag == 1 ? true : false, message: '请输入预期最高收益率!' },
                { validator: this.handleMaxValidator },
              ],
            },
            //*********************************  第六行 ********************************************/
            {
              dataIndex: 'expectLowReturn',
              title: '预期最低收益率',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '%',
              splitStyle: true,
              precision: 5,
              max: 99.99999,
              initialValue: type == 1 ? undefined : this.state.editObj?.expectLowReturn ? Number(this.state.editObj.expectLowReturn * 100).toFixed(5) : undefined,
              disabled: type == 3 ? true : isExpectReturnFlag == 1 ? false : true,
              rules: [
                // { pattern: /(^-?(?:\d|\d{0,8})(?:\.\d{0,5})?$)/, message: '字符不能超过8位！' },
                { required: isExpectReturnFlag == 1 ? true : false, message: '请输入预期最低收益率!' },
                { validator: this.handleMinValidator },
              ],
            },
            {
              dataIndex: 'manageFeeRate',
              title: '管理费率',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '%',
              splitStyle: true,
              precision: 5,
              max: 99.99999,
              initialValue: type == 1 ? 0 : this.state.editObj?.manageFeeRate ? Number(this.state.editObj.manageFeeRate * 100).toFixed(5) : 0,
              disabled: type == 3 ? true : false,
              rules: [
                // { pattern: /(^-?(?:\d|\d{0,8})(?:\.\d{0,5})?$)/, message: '字符不能超过8位！' },
                { required: isReportFlag, message: '请输入管理费率!' },
              ],
            },
            {
              dataIndex: 'trustFeeRate',
              title: '托管费率',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '%',
              splitStyle: true,
              precision: 5,
              max: 99.99999,
              initialValue: type == 1 ? 0 : this.state.editObj?.manageFeeRate ? Number(this.state.editObj.trustFeeRate * 100).toFixed(5) : 0,
              disabled: type == 3 ? true : false,
              rules: [
                // { pattern: /(^-?(?:\d|\d{0,8})(?:\.\d{0,5})?$)/, message: '字符不能超过8位！' },
                { required: isReportFlag, message: '请输入托管费率!' },
              ],
            },
            //*********************************  第七行 ********************************************/
            {
              dataIndex: 'dealRelateFeeRate',
              title: '交易相关合计费率',
              helper: '合同中标明的资产交易可能涉及的费用，包括税费、开户费、过户费、交易费等的合计费率',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '%',
              splitStyle: true,
              precision: 5,
              max: 99.99999,
              initialValue: type == 1 ? 0 : this.state.editObj?.dealRelateFeeRate ? Number(this.state.editObj.dealRelateFeeRate * 100).toFixed(5) : 0,
              disabled: type == 3 ? true : false,
              rules: [
                // { pattern: /(^-?(?:\d|\d{0,8})(?:\.\d{0,5})?$)/, message: '字符不能超过8位！' },
                { required: isReportFlag, message: '请输入交易相关合计费率!' },
              ],
            },
            {
              dataIndex: 'agencyFeeRate',
              title: '中介服务机构合计费率',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '%',
              splitStyle: true,
              precision: 5,
              max: 99.99999,
              initialValue: type == 1 ? 0 : this.state.editObj?.agencyFeeRate ? Number(this.state.editObj.agencyFeeRate * 100).toFixed(5) : 0,
              disabled: type == 3 ? true : false,
              rules: [
                // { pattern: /(^-?(?:\d|\d{0,8})(?:\.\d{0,5})?$)/, message: '字符不能超过8位！' },
                { required: isReportFlag, message: '请输入中介服务机构合计费率!' },
              ],
            },
            {
              dataIndex: 'otherFeeRate',
              title: '其他合计费率',
              helper: '合同中标明的，未包含在上述所列费用中的其他费用的合计费率',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '%',
              splitStyle: true,
              precision: 5,
              max: 99.99999,
              initialValue: type == 1 ? 0 : this.state.editObj?.otherFeeRate ? Number(this.state.editObj.otherFeeRate * 100).toFixed(5) : 0,
              disabled: type == 3 ? true : false,
              rules: [
                // { pattern: /(^-?(?:\d|\d{0,8})(?:\.\d{0,5})?$)/, message: '字符不能超过8位！' },
                { required: isReportFlag, message: '请输入其他合计费率!' },
              ],
            },
          ]}
          onRef={(ref) => {
            this.superviseStateInfoRef = ref;
          }}
        />
      </>
    );
  };

  render() {
    //操作类型,  1) 新增, 2) 编辑, 3) 详情, 4) 估值解析
    const { type } = this.props;
    return (
      <>
        <FixedButtonC
          topHtml={
            <div>
              <FirstHeaderC title={`委外信息维护-${type == 1 ? '新增' : type == 2 ? '编辑' : type == 3 ? '详情' : '估值解析'}`} />
              {type != 4 && (
                <>
                  <Row style={{ marginBottom: '10px' }}>
                    <Col>
                      {/* 基础信息 */}
                      {this.baseInfo()}
                    </Col>
                  </Row>
                  <Row style={{ marginBottom: '10px' }}>
                    <Col>
                      {/* 监管报表信息 */}
                      {this.superviseStateInfo()}
                    </Col>
                  </Row>
                  <AssetPackage
                    type={type} //仅在type=3时（查看详情）做置灰处理
                    initialData={type == 1 ? undefined : this.state.editObj?.titleValue ? this.state.editObj?.titleValue : undefined}
                    onRef={(e) => this.setState({ assetPackageRef: e })}
                  />
                </>
              )}
              {((type == 3 && !this.state.valuateAnalysisHide) || type == 4) && (
                <Row style={{ marginBottom: '10px' }}>
                  <Col>
                    {/* 估值解析 */}
                    <ValuateAnalysisInfo id={this.props.operateId} dimension={'2'} type={2} onRef={(e) => this.setState({ ref: e })} />
                  </Col>
                </Row>
              )}
            </div>
          }
          bottomHtml={
            <div style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
              <PrimaryGhostC style={{ margin: '0 10px' }} title='取消' onClick={this.onCancel} />
              {type != 3 && (
                <PrimaryC
                  style={{ margin: '0 10px' }}
                  title='确定'
                  onClick={this.onOk}
                  loading={
                    this.props.loading.effects['OutsourceInvestMsgMaintainM/saveData'] == true ||
                    this.props.loading.effects['OutsourceInvestMsgMaintainM/editData'] == true ||
                    this.props.loading.effects['OutsourceInvestMsgMaintainM/getDataById'] == true ||
                    this.props.loading.effects['OutsourceInvestMsgMaintainM/valuateAnalysis'] == true
                  }
                />
              )}
            </div>
          }
        />
      </>
    );
  }
}
